package controller;


import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import pojo.Exercise;
import pojo.ExerciseResult;
import service.ExerciseService;

import java.util.List;

@Controller
public class ExerciseController {
    @Autowired
    private ExerciseService exerciseService;

    @GetMapping("/main")
    public String toMainPage() {
        return "main";
    }

    @GetMapping("/exercise")
    public String generateExercise(@RequestParam("count") int count, HttpSession session, Model model) {
        try {
            if(count < 1 || count > 50){
                model.addAttribute("error", "题目数量必须在1-50之间，请重新输入");
                return "main";
            }
            // 调用Service生成题目
            List<Exercise> problems = exerciseService.generateExercises(count);
            // 将题目存入session，用于后续提交答案时比对
            session.setAttribute("problems", problems);
            // 传递题目到exercise.jsp
            model.addAttribute("problems", problems);
            return "exercise"; // 转发到exercise.jsp
        } catch (Exception e) {
            // 生成失败（如系统错误）
            model.addAttribute("error", "系统错误，请重试");
            return "main";
        }
    }

    @PostMapping("/submitExercise")
    public String submitExercise(@RequestParam("answers") List<Integer> userAnswers, HttpSession session, Model model) {
        // 从session中获取之前生成的题目
        @SuppressWarnings("unchecked")
        List<Exercise> problems = (List<Exercise>) session.getAttribute("problems");
        if (problems == null || userAnswers.size() != problems.size()) {
            model.addAttribute("error", "提交失败，请重新生成题目");
            return "main";
        }

        // 调用Service批改答案并生成结果
        ExerciseResult result = exerciseService.checkAnswers(problems, userAnswers);
        // 保存结果到文件
        exerciseService.saveResult(result);

        // 传递结果到result.jsp
        model.addAttribute("result", result);
        return "result"; // 转发到result.jsp
    }

    @GetMapping("/history")
    public String showHistory(Model model) {
        List<String> history = exerciseService.getHistory();
        model.addAttribute("history", history);
        return "history";
    }
}
